package com.axsoft.train;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


/**
 * Favorites Activity class
 * 
 * TODO: 
 * * Add context menu
 */
public class FavoritesActivity extends Activity implements OnItemClickListener {
	
	/**
	 * Activity created
	 */
	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.favorites);
	}
	
	
	/**
	 * Activity resumed
	 */
	@Override
	public void onResume() {
		super.onResume();
		initUi();
	}
	
	
	/**
	 * Initialize UI
	 */
	private void initUi() {
		final List<FavoritesItem> items = Constants.getFavorites(this);
		if (items == null) {
			Toast.makeText(this, getString(R.string.favorites_empty), Toast.LENGTH_LONG).show();
			return;
		}
		
		final FavoritesAdapter adapter = new FavoritesAdapter(getBaseContext(), android.R.layout.simple_list_item_1, items);
		((ListView) findViewById(R.id.FavoritesListView)).setAdapter(adapter);
	}
	
	
	
	/**
	 * An item was clicked
	 */
	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
		// TODO: Implement this method
	}
	
	
	/**
	 * Adapter class for favorites items
	 */
	private class FavoritesAdapter extends ArrayAdapter<FavoritesItem> 
	{
		private final List<FavoritesItem> mItems;
		
		/**
		 * Constructor
		 */
		public FavoritesAdapter(Context context, int textViewResourceId, List<FavoritesItem> items) {
			super(context, textViewResourceId, items);
			mItems = items;
		}
		
		/**
		 * Get View override
		 */
		@Override
		public View getView(int position, View view, ViewGroup parent) {
			
			if (view == null) {
				final LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				view = inflater.inflate(R.layout.favorites_row, null);
			}
			
			try {
				FavoritesItem item = mItems.get(position);
				// FIXME: Add favorite icon
				final TextView fromTV = (TextView) findViewById(R.id.FavoritesRowFrom);
				fromTV.setText(item.from);
				((TextView) findViewById(R.id.FavoritesRowTo)).setText(item.to);
				
				return view;
			} catch (Exception e) {
				Log.e("FavoritesAdapter.getView", e.toString());
				return view;
			}
		}
	}
}